#include "bhxjglrectangle.h"

BHXJGLRectangle::BHXJGLRectangle()
{

}
BHXJGLRectangle::~BHXJGLRectangle()
{
    if(this->gl!=nullptr)
    {
        gl->glDeleteVertexArrays(1,&VAO);
        gl->glInvalidateBufferData(EBO);
        gl->glInvalidateBufferData(VBO);
    }
}

void BHXJGLRectangle::Init(QOpenGLFunctions_4_3_Core *g, BHXJGLShader *s)
{
    this->gl=g;
    this->shader=s;

    float vertices[] = {
        //---- 位置 ----     - 纹理坐标 -
        1.0f,  1.0f, 0.,       1.0f, 1.0f,     // 右上
        1.0f, -1.0f, 0.,       1.0f, 0.0f,     // 右下
        -1.0f, -1.0f, 0.,      0.0f, 0.0f,     // 左下
        -1.0f,  1.0f, 0.,      0.0f, 1.0f      // 左上
    };
    unsigned int indices[] = { // 注意索引从0开始!
                               3, 1, 0, // 第一个三角形
                               3, 2, 1  // 第二个三角形
                             };
    gl->glGenVertexArrays(1,&VAO);
    gl->glGenBuffers(1,&VBO);
    gl->glGenBuffers(1,&EBO);

    gl->glBindVertexArray(VAO);

    gl->glBindBuffer(GL_ARRAY_BUFFER,VBO);
    gl->glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);

    gl->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);
    gl->glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);

    gl->glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,5*sizeof(float),nullptr);
    gl->glEnableVertexAttribArray(0);

    gl->glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,5*sizeof(float),reinterpret_cast<void*>(3*sizeof(float)));
    gl->glEnableVertexAttribArray(1);


    gl->glBindVertexArray(0);
    gl->glBindBuffer(GL_ARRAY_BUFFER, 0);
    gl->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
}
void BHXJGLRectangle::Paint(const glm::vec2 &size, const glm::vec3 &position,const glm::vec3 &up,const glm::vec3 &right
                            ,const glm::mat4 &view,const glm::mat4 &projection)
{
    if(this->gl==nullptr||this->shader==nullptr)
        return;

    glm::mat4 model(1);
    model[0]=glm::vec4(glm::normalize(right),0);
    model[1]=glm::vec4(glm::normalize(up),0);
    model[2]=glm::vec4(glm::normalize(glm::cross(right,up)),0);
    model[3]=glm::vec4(position,1);
    model=glm::scale(model,glm::vec3(size/2.0f,1));

    this->shader->use();
    this->shader->setMat4("model",model);
    this->shader->setMat4("view",view);
    this->shader->setMat4("projection",projection);
    this->gl->glBindVertexArray(VAO);
    this->gl->glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,reinterpret_cast<void*>(0));
    this->gl->glBindVertexArray(0);

}
